package com.teamall.web.app.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.teamall.web.app.db.dao.AppCommonDao;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.teamall.core.common.Page;
import com.teamall.framework.exception.BaseAppException;
import com.teamall.framework.log.LogManager;
import com.teamall.framework.util.DateUtils;
import com.teamall.framework.util.Utils;
import com.teamall.web.app.common.ResultFactory;
import com.teamall.web.app.common.SysUserTokenPOGenerator;
import com.teamall.web.app.vo.AppAidProjectProgressVO;
import com.teamall.web.app.vo.AppAidProjectVO;
import com.teamall.web.app.vo.AppProjectGroupByTypeVO;
import com.teamall.web.app.vo.AppProjectTypeVO;
import com.teamall.web.base.vo.ResResult;
import com.teamall.web.fpxm.db.po.AidProjectPO;
import com.teamall.web.fpxm.db.po.AidProjectProgressPO;
import com.teamall.web.fpxm.db.po.CodeAidProjectByAidstaffPO;
import com.teamall.web.fpxm.db.po.CodeAidProjectPO;
import com.teamall.web.fpxm.db.po.CodeAidProjectProgressPO;
import com.teamall.web.fpxm.service.IAidProjectProgressService;
import com.teamall.web.fpxm.service.IAidProjectService;
import com.teamall.web.fpxm.service.ICodeAidProjectByAidstaffService;
import com.teamall.web.fpxm.service.ICodeAidProjectProgressService;
import com.teamall.web.fpxm.service.ICodeAidProjectService;
import com.teamall.web.sys.db.po.DataDictPO;
import com.teamall.web.sys.db.po.SysUserPO;
import com.teamall.web.sys.db.po.SysUserTokenPO;
import com.teamall.web.sys.service.IDataDictService;
import com.teamall.web.sys.service.ISysUserService;

/**
 * ${DESCRIPTION}
 *
 * @author
 * @create 2017-07-01 23:38
 **/
@Controller
@RequestMapping("/app/project")
public class AppProjectController {
    private static final LogManager logger = LogManager
            .getLogger(AppProjectController.class);

    @Autowired
    private IAidProjectService aidProjectService;

    @Autowired
    private IAidProjectProgressService aidProjectProgressService;

    @Autowired
    private IDataDictService dataDictService;

    @Autowired
    private ICodeAidProjectService codeAidProjectService;

    @Autowired
    private ICodeAidProjectProgressService codeAidProjectProgressService;

    @Autowired
    private ISysUserService sysUserService;
    
    @Autowired
    private ICodeAidProjectByAidstaffService codeAidProjectByAidstaffService;

    @Autowired
    private AppCommonDao appCommonDao;

    /**
     * 3.4.2. 项目类型查询
     * 
     * @return
     */
    @RequestMapping("/getTypeList")
    @ResponseBody
    public ResResult getTypeList() {
        try {
            ResResult resResult = new ResResult();
            // 项目类型的数字字典 300
            DataDictPO qryProTypeDD = new DataDictPO();
            qryProTypeDD.setDataGroup(300);
            List<DataDictPO> proTypeDDList = dataDictService
                    .selectByArg(qryProTypeDD);
            List<AppProjectTypeVO> resultList = new ArrayList<AppProjectTypeVO>();
            for (DataDictPO oneDD : proTypeDDList) {
                AppProjectTypeVO oneProType = new AppProjectTypeVO();
                oneProType.setProjectType(oneDD.getDataKey());
                oneProType.setProjectTypeName(oneDD.getDataName());
                resultList.add(oneProType);
            }
            resResult.setRspData(resultList);
            return resResult;
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
    }

    /**
     * 3.4.3. 项目列表查询
     * 
     * @param projectType
     * @param projectName
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResResult list(
            HttpServletRequest request,
            @RequestParam(value = "projectType", required = true) Integer projectType,
            @RequestParam(value = "projectName", required = false) String projectName,
            @RequestParam(value = "projectYear", required = false) String projectYear,
            @RequestParam(value = "page", required = true) Integer page,
            @RequestParam(value = "rows", required = true) Integer rows) {

        if (Utils.isEmpty(projectType) || Utils.isEmpty(page)
                || Utils.isEmpty(rows)) {
            return ResultFactory.getRequestParamsError();
        }
        try {

            CodeAidProjectByAidstaffPO qryVO = new CodeAidProjectByAidstaffPO();
            if (projectType >= 0) {
                qryVO.setProjectType(projectType);
            }
            qryVO.setProjectName(projectName);

            if (Utils.notEmpty(projectYear)) {
                // 根据传入的年份，拼出当年第一天，最后一天
                Date sDate = DateUtils.string2Date(projectYear + "0101",
                        DateUtils.STR_DATE_FORMAT_DAY_WITHOUT_SPLIT);
                Date eDate = DateUtils.string2Date(projectYear + "1231",
                        DateUtils.STR_DATE_FORMAT_DAY_WITHOUT_SPLIT);
                qryVO.setBeginDate(sDate);
                qryVO.setEndDate(eDate);
            }
            String token = request.getHeader("token");
            SysUserTokenPO sysUserTokenPO = SysUserTokenPOGenerator
                    .getUserByToken(token);
            SysUserPO sysUserPO = sysUserService
                    .selectByPrimaryKey(sysUserTokenPO.getUserId());
            int aidMainStaff = sysUserPO.getUserObjId();//AID_STAFF的STAFF_ID，也就是FAMILY_INFO表的AID_MAIN_STAFF
            
            qryVO.setAidMainStaff(aidMainStaff);
            

            Page<CodeAidProjectByAidstaffPO> vPage = new Page<CodeAidProjectByAidstaffPO>();
            vPage.setPage(page);
            vPage.setRows(rows);
            
            codeAidProjectByAidstaffService.selectByArgAndPage(qryVO, vPage);

            Page<AppAidProjectVO> resultPage = new Page<AppAidProjectVO>();
            BeanUtils.copyProperties(vPage, resultPage);

            List<CodeAidProjectByAidstaffPO> vList = vPage.getResultList();
            List<AppAidProjectVO> resultList = new ArrayList<AppAidProjectVO>(
                    rows);
            for (CodeAidProjectByAidstaffPO vPO : vList) {
                AppAidProjectVO rVO = new AppAidProjectVO();
                BeanUtils.copyProperties(vPO, rVO);
                Integer benefitCount = appCommonDao.getBenefitCountByProjectId(rVO.getProjectId());
                rVO.setBenefitCount(benefitCount);
                resultList.add(rVO);
            }
            resultPage.setResultList(resultList);

            ResResult resResult = new ResResult();
            resResult.setRspData(resultPage);
            return resResult;
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
    }

    /**
     * 3.4.4. 项目进度查询
     * 
     * @param projectId
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping("/projectProgressList")
    @ResponseBody
    public ResResult projectProgressList(@RequestParam(value = "projectId",
            required = true) Integer projectId, @RequestParam(value = "page",
            required = true) Integer page, @RequestParam(value = "rows",
            required = true) Integer rows) {
        if (Utils.isEmpty(projectId) || Utils.isEmpty(page)
                || Utils.isEmpty(rows)) {
            return ResultFactory.getRequestParamsError();
        }
        try {
            CodeAidProjectProgressPO qryVO = new CodeAidProjectProgressPO();
            qryVO.setProjectId(projectId);

            Page<CodeAidProjectProgressPO> vPage = new Page<CodeAidProjectProgressPO>();
            vPage.setPage(page);
            vPage.setRows(rows);
            codeAidProjectProgressService.selectByArgAndPage(qryVO, vPage);

            Page<AppAidProjectProgressVO> resultPage = new Page<AppAidProjectProgressVO>();
            BeanUtils.copyProperties(vPage, resultPage);

            List<CodeAidProjectProgressPO> vList = vPage.getResultList();
            List<AppAidProjectProgressVO> resultList = new ArrayList<AppAidProjectProgressVO>(
                    rows);
            for (CodeAidProjectProgressPO vPO : vList) {
                AppAidProjectProgressVO rVO = new AppAidProjectProgressVO();
                BeanUtils.copyProperties(vPO, rVO);

                resultList.add(rVO);
            }
            resultPage.setResultList(resultList);

            ResResult resResult = new ResResult();
            resResult.setRspData(resultPage);
            return resResult;
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
    }

    /**
     * 3.4.5. 项目进度汇报
     * 
     * @param po
     * @return
     * @throws BaseAppException
     */
    @RequestMapping("/addProjectProgress")
    @ResponseBody
    public ResResult addProjectProgress(HttpServletRequest request,
            AidProjectProgressPO po) throws BaseAppException {
        if (Utils.isEmpty(po.getProjectId())
                || Utils.isEmpty(po.getPhotoList())
                || Utils.isEmpty(po.getCreateDate())
                || Utils.isEmpty(po.getMonth())
                || Utils.isEmpty(po.getContent())
                || Utils.isEmpty(po.getPeriodOfMonth())) {
            return ResultFactory.getRequestParamsError();
        }
        ResResult resResult = new ResResult();
        try {
            String token = request.getHeader("token");
            SysUserTokenPO sysUserTokenPO = SysUserTokenPOGenerator
                    .getUserByToken(token);
            SysUserPO sysUserPO = sysUserService
                    .selectByPrimaryKey(sysUserTokenPO.getUserId());
            int userObjId = sysUserPO.getUserObjId();
            po.setStaffId(userObjId);
            int pkId = aidProjectProgressService.add(po);
            resResult.setRspData(pkId);
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
        return resResult;
    }

    /**
     * 3.4.1. 项目全部分类以及项目查询
     * 
     * @param projectType
     * @return
     */
    @RequestMapping("/getProjectGroupByType")
    @ResponseBody
    public ResResult getProjectGroupByType(Integer projectType) {

        try {
            ResResult result = new ResResult();
            // Map<Integer, List<AppProjectGroupByTypeVO>> resultMap = new TreeMap<Integer, List<AppProjectGroupByTypeVO>>();

            // 项目类型的数字字典 300
            DataDictPO qryProTypeDD = new DataDictPO();
            qryProTypeDD.setDataGroup(300);
            List<DataDictPO> proTypeDDList = dataDictService
                    .selectByArg(qryProTypeDD);

            ProjectGroupByTypeRes[] resuleAry = null;

            if (Utils.notEmpty(projectType)) {
                resuleAry = new ProjectGroupByTypeRes[1];
            }
            else {
                resuleAry = new ProjectGroupByTypeRes[proTypeDDList.size()];
            }
            int index = 0;
            for (DataDictPO oneDD : proTypeDDList) {
                ProjectGroupByTypeRes oneRes = new ProjectGroupByTypeRes();
                oneRes.setProjectType(oneDD.getDataKey());
                oneRes.setProjectName(oneDD.getDataName());
                int proType = oneDD.getDataKey();
                // 如果单独查某个类型的
                if (Utils.notEmpty(projectType)) {
                    if (proType != projectType) {
                        continue;
                    }
                }
                AidProjectPO qryProjectPO = new AidProjectPO();
                qryProjectPO.setProjectType(proType);
                // 只捞 项目实施 状态的记录
                qryProjectPO.setState(1);
                List<AidProjectPO> oneProList = aidProjectService
                        .selectByArg(qryProjectPO);
                // List<AppProjectGroupByTypeVO> oneProVOList = new ArrayList<AppProjectGroupByTypeVO>();

                for (AidProjectPO onePro : oneProList) {
                    AppProjectGroupByTypeVO oneProVO = new AppProjectGroupByTypeVO();
                    BeanUtils.copyProperties(onePro, oneProVO);
                    // oneProVOList.add(oneProVO);
                    oneRes.getProjectList().add(oneProVO);
                }
                // resultMap.put(proType, oneProVOList);
                resuleAry[index] = oneRes;
                index++;
            }

            // result.setRspData(resultMap);
            result.setRspData(resuleAry);
            return result;
        }
        catch (Exception e) {
            logger.error(e);
            return ResultFactory.getExceptionResult();
        }
    }

    public class ProjectGroupByTypeRes {
        private Integer projectType;

        private String projectName;

        List<AppProjectGroupByTypeVO> projectList = new ArrayList<AppProjectGroupByTypeVO>();

        /**
         * @return the projectType
         */
        public Integer getProjectType() {
            return projectType;
        }

        /**
         * @param projectType the projectType to set
         */
        public void setProjectType(Integer projectType) {
            this.projectType = projectType;
        }

        /**
         * @return the projectName
         */
        public String getProjectName() {
            return projectName;
        }

        /**
         * @param projectName the projectName to set
         */
        public void setProjectName(String projectName) {
            this.projectName = projectName;
        }

        /**
         * @return the projectList
         */
        public List<AppProjectGroupByTypeVO> getProjectList() {
            return projectList;
        }

        /**
         * @param projectList the projectList to set
         */
        public void setProjectList(List<AppProjectGroupByTypeVO> projectList) {
            this.projectList = projectList;
        }

    }
}
